import 'dart:async';
import 'dart:math';

import 'package:factoryside/api/api.dart';
import 'package:factoryside/bean/order_list_entity.dart';
import 'package:factoryside/generated/json/order_list_entity_helper.dart';
import 'package:factoryside/home/page_create_order.dart';
import 'package:factoryside/home/page_order_detail.dart';
import 'package:factoryside/home/page_search_order_list.dart';
import 'package:factoryside/utils/ColorsUtils.dart';
import 'package:factoryside/utils/mock_request.dart';
import 'package:factoryside/utils/my_util.dart';
import 'package:factoryside/utils/request_util.dart';
import 'package:factoryside/utils/utils.dart';
import 'package:factoryside/widget/tabs.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

///工单区
class OrderPage extends StatefulWidget {
  int initialIndex=0;

  OrderPage({this.initialIndex=0});

  @override
  State<StatefulWidget> createState() {
    return _OrderState();
  }
}

class _OrderState extends State<OrderPage>
    with AutomaticKeepAliveClientMixin, TickerProviderStateMixin {
  TabController _tabController;

  @override
  void dispose() {
    super.dispose();
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

  List<String> stateTop = ['23', '2', '3', '12', '5'];

  var myTabs;

  List<Widget> pagesTop;

  @override
  void initState() {
    // TODO: implement initState
    print("page_order重绘了");
    super.initState();
    initData();
  }

  void initData() {
    this._tabController = TabController(initialIndex: widget.initialIndex,vsync: this, length: stateTop.length);
    pagesTop = stateTop.map((state) {
      return OrderSubPage(state);
    }).toList();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context); //必须实现 不然 在push过后页面会刷新
    // TODO: implement build
    return Scaffold(
        appBar: AppBar(
          brightness: Brightness.light,
          elevation: 0.1,
          backgroundColor: Colors.white,
//          toolbarHeight: 30,
          automaticallyImplyLeading: false,
//                title: Text('AppBar标题'),
          //添加选项卡按钮，注意此bottom表示在AppBar的底部，在整个页面上看还是处于顶部区域
          title: Text('工单区',
              style: TextStyle(
                  fontSize: 18,
                  color: Colors.black,
                  fontWeight: FontWeight.normal)),
          centerTitle: true,
          actions: [
            IconButton(
                icon: Image.asset(
                  'assets/search.png',
                  width: 20,
                  height: 20,
                ),
                onPressed: () {
                  push(context, SearchOrderPage());
                })
          ],
        ),
        body: Column(
          children: [
            Container(
              height: 40,
              color: Colors.white,
              child: getTabs(),
            ),
            Expanded(
              child: ExtendedTabBarView(
                controller: _tabController,
                children: pagesTop,
              ),
            ),
          ],
        ),
        floatingActionButton: FloatingActionButton(
          heroTag: null,
        onPressed: () async {
          push(context, CreateOrderPage(2));
          // ignore: deprecated_member_use
//          Scaffold.of(context).showSnackBar(
//            SnackBar(content: Text('Favorited')),
//          );
        },
        child: const Icon(Icons.add),
      ),
    );
  }

  TabBar getTabs() {
      myTabs = <Tab>[
        Tab(
          text: '进行中工单',
        ),
        Tab(
          text: '待结算工单',
        ),
        Tab(
          text: '已结算工单',
        ),
        Tab(
          text: '已取消工单',
        ),
        Tab(
          text: '全部工单',
        ),
      ];
    return buildTabBar();
  }

  TabBar buildTabBar() {
    return TabBar(
      controller: _tabController,
      isScrollable: true,
      unselectedLabelColor: Colors.black, //设置未选中时的字体颜色，tabs里面的字体样式优先级最高
      unselectedLabelStyle:
          TextStyle(fontSize: 15), //设置未选中时的字体样式，tabs里面的字体样式优先级最高
      labelColor:
          ColorsUtil.hexToColor('#2456ED'), //设置选中时的字体颜色，tabs里面的字体样式优先级最高
      labelPadding: EdgeInsets.symmetric(horizontal: 10, vertical: 5),
      labelStyle: TextStyle(
          fontSize: 15.0,
          fontWeight: FontWeight.bold), //设置选中时的字体样式，tabs里面的字体样式优先级最高
      indicatorColor: ColorsUtil.hexToColor('#2456ED'), //选中下划线的颜色
      indicatorPadding: EdgeInsets.symmetric(horizontal: 20, vertical: 5),
      indicatorSize:
          TabBarIndicatorSize.label, //选中下划线的长度，label时跟文字内容长度一样，tab时跟一个Tab的长度一样
      indicatorWeight: 2.0, //选中下划线的高度，值越大高度越高，默认为2。0
//                indicator: BoxDecoration(),//用于设定选中状态下的展示样式
      tabs: myTabs,
    );
  }
}

class OrderSubPage extends StatefulWidget {
  final String state;
  final String sendUser;

  OrderSubPage(this.state,{this.sendUser=''});

  @override
  _OrderSubPageState createState() => _OrderSubPageState();
}

class _OrderSubPageState extends State<OrderSubPage>
    with AutomaticKeepAliveClientMixin {
  var states = ['1', '6', '13', '14', '15', '16', '17', '18'];
  var page = 1;
  var limit = 10;
  List<OrderListEntity> items = [];
  List<Widget> orderlist= [];
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);
  ScrollController _controller = ScrollController();

  @override
  void initState() {
    super.initState();
    _fetchData(true);
  }

  void _fetchData(bool hasLoading) {
    RequestUtil.post(Api.getOrderList,{
      'State':widget.state,
      'SendUser':widget.sendUser,
      'page':page,
      'limit':limit
    }).then((value){
      List list=value['Data']['data'];
      List<OrderListEntity> tempList=[];
      list.forEach((element) {
        tempList.add(orderListEntityFromJson(OrderListEntity(),element));
      });
      if (page == 1) {
        items=tempList;
        _refreshController.resetNoData();
      } else {
        if (tempList.length == 0) {
          _refreshController.loadNoData();
        } else {
          items.addAll(tempList);
        }
      }
      orderlist=items.asMap().keys.map((i){
        return OrderCell(
            topHeight: states.contains(widget.state),
            index: i,
            order: items[i],
            c: context);
      }).toList();
      if (mounted) {
        setState(() {

              });
      }
    });
  }

  @override
  void dispose() {
    print('dispose');
    _refreshController.dispose();
    super.dispose();
  }

  void _onRefresh() async {
    await Future.delayed(Duration(milliseconds: 1000));
    page = 1;
    _fetchData(false);
    _refreshController.refreshCompleted();
  }

  void _onLoading() async {
    await Future.delayed(Duration(microseconds: 1000));

    page++;
    _fetchData(false);
    _refreshController.loadComplete();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context); //必须实现 不然 在push过后页面会刷新
          return Container(
              color: ColorsUtil.hexToColor('#F2F2F2'),
              child: Column(
                children: [
                  Expanded(
                    child: items.length == 0
                        ? buildSmartRefresher(buildEmptyContainer())
                        : buildSmartRefresher(ListView(
                      controller: _controller,
                      children: orderlist,
                    )),
                  )
                ],
              ));
  }

  Container buildEmptyContainer() {
    return Container(
      color: Colors.white,
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image.asset(
              'assets/v3_nodata.png',
              width: 100,
              height: 100,
            ),
            Text(
              '暂无工单',
              style: TextStyle(color: Colors.grey),
            ),
          ],
        ),
      ),
    );
  }

  SmartRefresher buildSmartRefresher(Widget child) {
    return SmartRefresher(
      enablePullDown: true,
      enablePullUp: items.length != 0,
      controller: _refreshController,
      onRefresh: _onRefresh,
      onLoading: _onLoading,
      child: child,
    );
  }

  @override
  bool get wantKeepAlive => true;
}

// ignore: must_be_immutable
class OrderCell extends StatefulWidget {
   OrderCell({
    Key key,
    this.topHeight = false,
    @required this.index,
    @required this.order,
    @required this.c,
  }) : super(key: key);

  bool topHeight;
  int index;
  OrderListEntity order;
  BuildContext c;

   @override
  State<StatefulWidget> createState() {
    return OrderCellState();
  }
}

class OrderCellState extends State<OrderCell> {
  bool shrink = false;

  TextEditingController reasonCtr = TextEditingController();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    var prodlist = widget.order.prodcts;
    var name = '';
    for (int i = 0; i < prodlist.length; i++) {
      var prod = prodlist[i];
      var str1 = prod.brandName == null ? '' : prod.brandName + '(';
      var str2 = prod.subCategoryName == null ? '' : prod.subCategoryName + ')';
      var str3 = prod.prodModelName == null ? '' : prod.prodModelName + '、';
      var str4 = str1 + str2 + str3;
      name += str4;
    }
    if (name.contains('、')) {
      name = name.substring(0, name.lastIndexOf('、'));
    }
    return GestureDetector(
      child: buildCard(),
      onTap: () {
//        Navigator.push(context,
//            CupertinoPageRoute(builder: (BuildContext context) {
//          return OrderDetailPage(widget.order.orderID);
//        }));
      },
    );
  }

  GestureDetector buildCard() {
    var prodlist = widget.order.prodcts;
    var name = '';
    for (int i = 0; i < prodlist.length; i++) {
      var prod = prodlist[i];
      var str1 = prod.brandName == null ? '' : prod.brandName + '(';
      var str2 = prod.subCategoryName == null ? '' : prod.subCategoryName + ')';
      var str3 = prod.prodModelName == null ? '' : prod.prodModelName + '、';
      var str4 = str1 + str2 + str3;
      name += str4;
    }
    String orderType='';
    if(widget.order.guarantee=='Y'){
      orderType='保内${widget.order.typeName}';
    }else{
      orderType='保外${widget.order.typeName}';
    }
    if (name.contains('、')) {
      name = name.substring(0, name.lastIndexOf('、'));
    }
    var num=Random().nextInt(signs.length);
    return GestureDetector(
      child: Card(
          elevation: 0.0,
          margin: EdgeInsets.fromLTRB(10,10,10,0),
          child: Container(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
//            mainAxisAlignment: ,
              children: [
                //工单号
                InkWell(
                  onTap: () {
                    String copyText = "工单号：" +
                        widget.order.orderNumber +
                        "\n" +
                        "下单时间：" +
                        widget.order.createDate +
                        "\n" +
                        "用户信息：" +
                        widget.order.userName +
                        " " +
                        widget.order.phone +
                        "\n" +
                        "用户地址：" +
                        widget.order.address +
                        "\n" +
                        "产品信息：" +
                        name +
                        "\n" +
                        "售后类型：" +
                        (widget.order.guarantee == "Y" ? "保内" : "保外") +
                        "\n" +
                        "服务类型：" +
                        widget.order.typeName;
                    //复制
                    Clipboard.setData(ClipboardData(text: copyText));
                    showToast('复制成功');
                  },
                  child: Container(
                    padding: EdgeInsets.symmetric(horizontal: 10, vertical: 2),
                    decoration: BoxDecoration(
                        color: ColorsUtil.hexToColor('#D5D4D4'),
                        borderRadius: BorderRadius.only(
                            topLeft: Radius.circular(5),
                            topRight: Radius.circular(5))),
                    child: Row(
                      children: [
                        Expanded(
                          child: Text(
                            '工单号：${widget.order.orderNumber}',
                            style: TextStyle(fontSize: 14),
                          ),
                        ),
                        Image.asset(
                          'assets/copy.png',
                          width: 25,
                          height: 25,
                        )
                      ],
                    ),
                  ),
                ),
                Container(
                  padding: EdgeInsets.fromLTRB(10, 10, 10, 10),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Wrap(
                        spacing: 5,
                        runSpacing: 5,
                        children: List.generate(2,(element)=>Container(
                          padding: EdgeInsets.symmetric(
                              vertical: 3, horizontal: 5),
                          decoration: BoxDecoration(
                              color: colors[element],
                              borderRadius:
                              BorderRadius.all(Radius.circular(2))),
                          child: Text(
                            element==0?'${widget.order.stateHtml}':'${orderType}',
                            style: TextStyle(
                                fontSize: 10, color: Colors.white),
                            textAlign: TextAlign.center,
                          ),
                        )).toList(),
                      ),
                      SizedBox(height: 10,),
                      buildProd(widget.order),
                      //地址
                      Row(
                          crossAxisAlignment: CrossAxisAlignment.end,
                          children: [
                            Expanded(
                                child: Text(
                                  widget.order.address,
                              style: TextStyle(
                                  color: Colors.black54, fontSize: 14),
                              maxLines: 2,
                              overflow: TextOverflow.ellipsis,
                            ))
                          ]),
                      SizedBox(
                        height: 5,
                      ),
                      //距离和时间
                      Row(
                        children: [
                          Padding(
                            padding: EdgeInsets.only(left: 0),
                            child: Row(
                              children: [
                                Image.asset(
                                  'assets/time.png',
                                  width: 15,
                                  height: 15,
                                ),
                                SizedBox(
                                  width: 5,
                                ),
                                Text(MyUtil.getTimebefore(widget.order.createDate),
                                    style: TextStyle(fontSize: 12)),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                )
              ],
            ),
          )),
      onTap: () {
        push(context, OrderDetailPage(widget.order.orderID));
      },
    );
  }

  Widget buildProd(OrderListEntity order) {
    if (shrink) {
      return Column(
        children: [
          Column(
            children:
                order.prodcts.map((e) => buildContainer(e)).toList(),
          ),
          SizedBox(height: 5),
          buildInkWell(),
          SizedBox(height: 5),
        ],
      );
    } else {
      return Column(
        children: [
          buildContainer(order.prodcts[0]),
          SizedBox(height: 5),
          Visibility(
              visible: order.prodcts.length > 1,
              child: buildInkWell()),
          SizedBox(height: 5),
        ],
      );
    }
  }

  InkWell buildInkWell() {
    return InkWell(
      onTap: () {
        this.setState(() {
          shrink = !shrink;
        });
      },
      child: Row(
        children: [
          Expanded(child: Divider(height: 1)),
          Row(
            children: [
              Text(shrink ? '收起' : '展开', style: TextStyle(fontSize: 13)),
              Icon(
                shrink ? Icons.keyboard_arrow_up : Icons.keyboard_arrow_down,
                size: 15,
              )
            ],
          ),
          Expanded(child: Divider(height: 1)),
        ],
      ),
    );
  }

  Container buildContainer(OrderListProdct prod) {
    return Container(
      margin: EdgeInsets.only(bottom: 2),
      padding: EdgeInsets.all(6),
      decoration: BoxDecoration(
          color: ColorsUtil.hexToColor('#f2f2f2'),
          borderRadius: BorderRadius.all(Radius.circular(5))),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Expanded(
                child: Text(
                  prod.subCategoryName + '  ' + prod.productType,
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.w500),
                  maxLines: 2,
                ),
              ),
            ],
          ),
          SizedBox(
            height: 5,
          ),
          //服务要求memo
          Container(
//                    height: 30,
              child: Text(
                prod.memo,
//            '更换排水牵引器，配件已排发用户处韵达快递单号4301205945476.型号ⅩQB85-1198购买日期2019.6',
            style: TextStyle(color: Colors.grey, fontSize: 14),
            maxLines: 2,
            overflow: TextOverflow.ellipsis,
          )),
        ],
      ),
    );
  }
}
